package com.yazi.mxz.server.controller;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.annotation.JsonView;
import com.yazi.mxz.common.entity.beans.Region;
import com.yazi.mxz.common.service.RegionService;
import com.yazi.mxz.server.response.RegionListResponse;
import com.yazi.mxz.server.response.view.BaseView;

@Controller("regionController")
@RequestMapping("/region")
public class RegionController extends BaseController {
	private static Logger log = LoggerFactory.getLogger(RegionController.class);

	@Resource
	RegionService regionService;

	@RequestMapping("/listByParentId")
	@ResponseBody
	@JsonView(BaseView.class)
	public RegionListResponse listByParentIdJson(@RequestBody Long parentId) {
		log.debug("用户  -> 地区json数据");
		RegionListResponse jsonResult = new RegionListResponse();
		
		try{
			// 默认加载"南宁"下的地区
			if (null == parentId) {
				parentId = 97L;
			}
			Region region = new Region();
			region.setParentId(parentId);
			List<Region> regions = regionService.search(region, null, null);
			
			jsonResult.setSuccessData(regions);
			jsonResult.setOk();
		} catch (Exception e) {
			log.error("用户 - > 获取地区列表异常", e);
			jsonResult.setErrorMessage("加载失败!");
		}
		return jsonResult;
	}
	
	@RequestMapping("/listBrothers")
	@ResponseBody
	@JsonView(BaseView.class)
	public RegionListResponse listBrothersJson(@RequestBody Long regionId) {
		log.debug("用户  -> 地区json数据");
		RegionListResponse jsonResult = new RegionListResponse();
		
		try{
			Region region = regionService.oneById(regionId);
			if (region.getRegionType() > 0) {
				Region regionForSearch = new Region();
				regionForSearch.setParentId(region.getParentId());
				List<Region> regions = regionService.search(regionForSearch, null, null);
				jsonResult.setSuccessData(regions);
			}
			jsonResult.setOk();
		} catch (Exception e) {
			log.error("用户 - > 获取兄弟地区列表异常", e);
			jsonResult.setErrorMessage("加载失败!");
		}
		return jsonResult;
	}
	
}
